package com.fang.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fang.common.dto.param.SysMenuAddParam;
import com.fang.common.dto.param.SysMenuUpdateParam;
import com.fang.common.dto.result.SysMenuResult;
import com.fang.common.wrapper.ResponseWrapper;
import com.fang.entity.SysMenu;
import com.fang.entity.SysRoleMenu;
import com.fang.entity.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.security.Principal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Fang Ruichuan
 * @since 2022-08-27
 */
@RestController
@Api(value = "菜单管理器", tags = "菜单管理器")
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController {


    @ApiOperation(value = "获取当前用户菜单和权限")
    @GetMapping("/nav")
    public ResponseWrapper nav(Principal principal) {
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        // 获取权限信息
        String authorityInfo = sysUserService.getUserAuthorityInfo(sysUser.getId());
        String[] authorityInfoArray = StringUtils.tokenizeToStringArray(authorityInfo, ",");
        // 获取导航栏信息
        List<SysMenuResult> sysMenuResults = sysMenuService.getCurrentUserNav();
        return ResponseWrapper.success(MapUtil.builder()
                .put("authorities", authorityInfoArray)
                .put("nav", sysMenuResults)
                .map());
    }

    @GetMapping("/info/{id}")
    @ApiOperation(value = "根据ID获取某项菜单信息")
    public ResponseWrapper info(@PathVariable("id") Long id) {
        return ResponseWrapper.success(sysMenuService.getById(id));
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    @ApiOperation(value = "获取菜单列表")
    public ResponseWrapper list() {
        return ResponseWrapper.success(sysMenuService.tree());
    }

    @PostMapping("/save")
    @ApiOperation(value = "添加菜单")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public ResponseWrapper save(@RequestBody @Validated SysMenuAddParam sysMenuAddParam) {
        SysMenu sysMenu = new SysMenu();
        BeanUtils.copyProperties(sysMenuAddParam, sysMenu);
        sysMenu.setCreated(LocalDateTime.now());
        sysMenuService.save(sysMenu);
        return ResponseWrapper.success();
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新菜单")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public ResponseWrapper update(@RequestBody @Validated SysMenuUpdateParam sysMenuUpdateParam) {
        SysMenu sysMenu = new SysMenu();
        BeanUtils.copyProperties(sysMenuUpdateParam, sysMenu);
        sysMenu.setUpdated(LocalDateTime.now());
        sysMenuService.updateById(sysMenu);
        // 清除所有与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return ResponseWrapper.success();
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据ID删除菜单")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public ResponseWrapper delete(@PathVariable("id") Long id) {
        int count = sysMenuService.count(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getParentId, id));
        if (count > 0) {
            return ResponseWrapper.fail("请先删除子菜单");
        }
        // 清除所有与该菜单相关的权限缓存
        sysUserService.clearUserAuthorityInfoByMenuId(id);
        sysMenuService.removeById(id);
        // 同步删除中间关联表
        sysRoleMenuService.remove(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getMenuId, id));
        return ResponseWrapper.success();
    }


}
